'use strict';

const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  console.log('【debugUserBalance】调试用户余额:', event);
  
  const { userId } = event;
  
  try {
    // 1. 查找用户信息
    const userRes = await db.collection('uni-id-users')
      .doc(userId)
      .get();
    
    console.log('【debugUserBalance】用户信息:', userRes.data);
    
    if (!userRes.data || userRes.data.length === 0) {
      return {
        code: 404,
        msg: '用户不存在',
        data: null
      };
    }
    
    const user = userRes.data[0];
    const currentBalance = user.balance || 0;
    
    console.log('【debugUserBalance】当前余额:', currentBalance);
    
    // 2. 尝试增加余额
    const testAmount = 1; // 测试增加1元
    const balanceUpdateResult = await db.collection('uni-id-users')
      .doc(userId)
      .update({
        balance: dbCmd.inc(testAmount)
      });
    
    console.log('【debugUserBalance】余额更新结果:', balanceUpdateResult);
    
    // 3. 再次查询用户信息
    const userRes2 = await db.collection('uni-id-users')
      .doc(userId)
      .get();
    
    const newBalance = userRes2.data[0].balance || 0;
    
    console.log('【debugUserBalance】更新后余额:', newBalance);
    
    return {
      code: 200,
      msg: '调试完成',
      data: {
        userId,
        originalBalance: currentBalance,
        testAmount: testAmount,
        newBalance: newBalance,
        balanceUpdated: balanceUpdateResult.updated,
        userExists: true
      }
    };
    
  } catch (error) {
    console.error('【debugUserBalance】调试失败:', error);
    return {
      code: 500,
      msg: '调试失败',
      error: error.message
    };
  }
};